package handler

import (
	"github.com/gin-gonic/gin"
	"golang-websocket-chatroom/model"
	"golang-websocket-chatroom/repository"
	"golang-websocket-chatroom/request"
	"golang-websocket-chatroom/response"
)

func RoomAdd(c *gin.Context) {
	var req request.RoomAdd
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	room := model.Room{
		UserId: c.GetUint("userId"),
		Name:   req.Name,
	}
	repository.Create(&room)
	roomUser := model.RoomUser{

		UserId:   room.UserId,
		RoomId:   room.Id,
		Type:     1,
		Describe: "群主",
	}
	repository.Create(&roomUser)
	if room.Id == 0 {
		response.ResponseError(c, "群创建失败", nil)
		return
	}
	if roomUser.Id == 0 {
		response.ResponseError(c, "群成员添加失败", nil)
		return
	}
	response.ResponseSuccess(c, "群创建成功", room)
}

func RoomAddUser(c *gin.Context) {
	var req []request.RoomAddUser
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	userId := c.GetUint("user_id")
	roomUser := model.RoomUser{}
	repository.WhereList(&model.RoomUser{UserId: userId}, &roomUser)
	if roomUser.Type != 1 && roomUser.Type != 2 {
		response.ResponseError(c, "不是群主或者管理员", nil)
		return
	}
	for _, addUser := range req {
		roomUser = model.RoomUser{
			UserId:   addUser.UserId,
			RoomId:   addUser.RoomId,
			Type:     3,
			Describe: addUser.Describe,
		}
		repository.Create(&roomUser)
	}
	response.ResponseSuccess(c, "成员添加成功", roomUser)
}

func RoomList(c *gin.Context) {
	var req request.RoomListUser
	err := c.ShouldBind(&req)
	if err != nil {
		response.ResponseError(c, "错误", err.Error())
		return
	}
	room := []model.RoomUser{}
	repository.WhereLists(&model.RoomUser{RoomId: req.RoomId}, &room)
	response.ResponseSuccess(c, "成功", room)

}
